<template>
  <div class="bgc-white p24" style="min-height: calc(100vh - 112px)">
    <div class="flex">
      <SelectCompanyGroup :hasLeftIcon="true" :selectTreeId.sync="siteId" :type.sync="type" />
    </div>
    <div class="mv12 p12">
      <ListStats ref="stats" :status.sync="status" :params="params" />
    </div>
    <div>
      <div class="flex-center-between">
        <a-space :size="16">
          <a-input-search v-model="nameOrIdCard" placeholder="姓名/身份证号" style="width: 200px" @change="onInputChange('nameOrIdCard')" />
          <a-input-search v-model="schemeName" placeholder="商保方案" style="width: 200px" @change="onInputChange('schemeName')" />
          <a-input-search v-model="insCompanyName" placeholder="保险公司" style="width: 200px" @change="onInputChange('insCompanyName')" />
          <a-range-picker
            :value="dateRange"
            :placeholder="['在保开始时间', '结束时间']"
            :mode="['date', 'date']"
            format="YYYY-MM-DD"
            style="width: 240px"
            @panelChange="onPanelChange"
            @change="onRangeChange"
          />
        </a-space>
        <a-space :size="16">
          <a-button v-if="hasExport" @click="doExport">全部导出</a-button>
          <a-button v-if="hasAdd" type="primary" @click="selectVisible = true">新增在保</a-button>
        </a-space>
      </div>
    </div>
    <div class="mt24">
      <a-table
        :columns="columnsList"
        :dataSource="dataSource"
        :pagination="pagination"
        :scroll="{ x: true }"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <div slot="empName" slot-scope="text, record" style="position: relative">
          <img
            v-if="record.paymentType === '年保'"
            src="./nianbao.png"
            style="width: 45px; height: 46px; position: absolute; top: -16px; left: -16px"
          />
          {{ text }}
        </div>
        <template slot="dateRange" slot-scope="text, record">
          {{ formatDate(record.beginTime) }}-{{ formatDate(record.endTime) }}
        </template>
        <template slot="action" slot-scope="text, record">
          <a-space>
            <span class="pointer tc-theme" @click="doDetail(record)">详情</span>
          </a-space>
        </template>
      </a-table>
    </div>
    <SelectEmployee v-model="selectVisible" @confirm="onEmpSelected" />
    <SelectConfirm v-model="confirmVisible" @confirm="doConfirm" />
    <ListDetail v-model="detailVisible" :target="currentEmp" @close="onSearchChange" />
    <a-modal v-model="resultVisible" title="参保结果" width="1000px" @cancel="resultClear" @ok="doResultConfirm">
      <Result v-if="resultData" :resultData="resultData" />
    </a-modal>
  </div>
</template>
<script>
import ListStats from "./listStats.vue";
import { filterEmptyValue } from "@/utils/tools";
import { columnsList } from "./funcs";
import SelectCompanyGroup from "@/components/SelectCompany";
import SelectEmployee from "./selectEmployee.vue";
import SelectConfirm from "./selectConfirm.vue";
import ListDetail from "./listDetail.vue";
import { mapGetters } from "vuex";
import Result from "./result.vue";
import { getToken } from "xqjr-module-auth/utils";
export default {
  name: "",
  components: { ListStats, SelectCompanyGroup, SelectEmployee, SelectConfirm, ListDetail, Result },
  mixins: [],
  props: {},
  data() {
    return {
      resultVisible: false,
      resultData: null,
      currentEmp: null,
      detailVisible: false,
      confirmVisible: false,
      selectVisible: false,
      columnsList,
      status: 1,
      nameOrIdCard: "",
      schemeName: "",
      insCompanyName: "",
      dateRange: null,
      params: {
        status: 1
      },
      siteId: "",
      type: "",
      dataSource: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      },
      empLst: [],
      loading: false
    };
  },
  computed: {
    ...mapGetters(["permissions_shangbao"]),
    hasExport() {
      return this.permissions_shangbao.includes("insuranceAddService:insuranceAddService.zaibaorenyuan:exportIns");
    },
    hasAdd() {
      return this.permissions_shangbao.includes("insuranceAddService:insuranceAddService.zaibaorenyuan:addIns");
    }
  },
  watch: {
    siteId() {
      this.params = {
        ...this.params,
        type: {
          id: this.siteId,
          type: this.type
        }
      };
    },
    status(newVal) {
      this.params = {
        ...this.params,
        status: newVal
      };
    },
    params: {
      handler() {
        this.onSearchChange();
      },
      deep: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    doResultConfirm() {
      this.resultClear();
      this.pagination.current = 1;
      this.onSearchChange();
    },
    resultClear() {
      this.resultVisible = false;
      this.resultData = null;
    },
    doDetail(item) {
      this.currentEmp = item;
      setTimeout(() => {
        this.detailVisible = true;
      }, 0);
    },
    formatDate(val) {
      if (val) {
        return this.$dayjs(val).format("YYYY-MM-DD");
      }
      return "--";
    },
    doExport() {
      this.$axios({
        url: `/hr/api/v1/hrInsurance/exportList`,
        method: "post",
        data: this.params,
        responseType: "blob",
        headers: {
          token: getToken(),
          "Content-Type": "application/json"
        }
      })
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const rspHeaders = res.headers;
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            if (rspHeaders["content-disposition"]) {
              try {
                const fileName = decodeURI(rspHeaders["content-disposition"].split(";")[1].split("=")[1].replaceAll('"', ""));
                const fileNameArr = fileName.split(".");
                link.download = "商保记录." + fileNameArr[1];
                link.click();
                URL.revokeObjectURL(link.href);
                document.body.removeChild(link);
              } catch (err) {
                console.log("error log --> ", err);
              }
            } else {
              this.$notification.error({ message: "下载失败" });
            }
          }
        })
        .catch((err) => {
          console.log("hrInsurance/exportList", err);
        });
    },
    doConfirm(params) {
      this.$request({
        url: `/insurance/api/v1/qyInsuranceRecords/addInsurance`,
        method: "post",
        data: {
          ...params,
          empList: this.empLst.map((item) => ({
            id: item.id,
            name: item.name,
            idCard: item.idCard,
            phone: item.phone,
            companyId: item.companyId,
            companyName: item.companyName
          }))
        }
      })
        .then((res) => {
          this.confirmVisible = false;
          this.pagination.current = 1;
          this.onSearchChange();
          this.resultData = res.data;
          if (this.resultData.errorCount) {
            this.resultVisible = true;
          }
        })
        .catch((err) => {
          console.log("qyInsuranceRecords/addInsurance", err);
        });
    },
    onEmpSelected(empLst) {
      if (empLst.length <= 0) {
        this.$message.warning("未选择参保人员");
        return false;
      }
      this.empLst = empLst;
      this.confirmVisible = true;
    },
    onInputChange(key) {
      this.params = filterEmptyValue({
        ...this.params,
        [`${key}`]: this[key]
      });
    },
    onRangeChange(value) {
      this.dateRange = value;
      const params = {};
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM-DD"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      } else {
        params["beginTime"] = null;
        params["endTime"] = null;
      }
      this.params = filterEmptyValue({
        ...this.params,
        ...params
      });
    },
    onPanelChange(value) {
      this.dateRange = value;
      const params = {};
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM-DD"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      } else {
        params["beginTime"] = null;
        params["endTime"] = null;
      }
      this.params = filterEmptyValue({
        ...this.params,
        ...params
      });
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.onSearchChange();
    },
    onSearchChange() {
      this.loading = true;
      this.$request({
        url: `/hr/api/v1/hrInsurance/selectPage`,
        method: "post",
        data: {
          ...this.params,
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        }
      })
        .then((res) => {
          this.dataSource = res.data.entities;
          this.pagination.total = res.data.entityCount;
          this.loading = false;
          if (this.pagination.current === 1) {
            this.$refs.stats.loadData();
          }
        })
        .catch((err) => {
          console.log("hrInsurance/selectPage", err);
          this.loading = false;
        });
    }
  }
};
</script>
<style lang="scss"></style>
